def merge_dictionaries(dict1, dict2):
    """
    合并两个字典，如果键重复则后者覆盖前者

    Args:
        dict1 (dict): 第一个字典
        dict2 (dict): 第二个字典

    Returns:
        dict: 合并后的新字典

    Raises:
        TypeError: 如果输入不是字典类型

    Example:
        >>> dict1 = {'a': 1, 'b': 2}
        >>> dict2 = {'b': 3, 'c': 4}
        >>> merge_dictionaries(dict1, dict2)
        {'a': 1, 'b': 3, 'c': 4}
    """
    # 输入验证
    if not isinstance(dict1, dict) or not isinstance(dict2, dict):
        raise TypeError("两个参数都必须是字典类型")

    # 创建新字典而不是修改原字典
    merged_dict = dict1.copy()  # 复制第一个字典
    merged_dict.update(dict2)  # 用第二个字典更新，重复键会被覆盖

    return merged_dict


def merge_dictionaries_advanced(*dicts, **kwargs):
    """
    高级版本：合并多个字典，支持自定义冲突处理

    Args:
        *dicts: 要合并的多个字典
        **kwargs: 可选参数
            conflict_handler: 冲突处理方式，'first'|'last'|'error'

    Returns:
        dict: 合并后的字典

    Example:
        >>> dict1 = {'a': 1, 'b': 2}
        >>> dict2 = {'b': 3, 'c': 4}
        >>> dict3 = {'c': 5, 'd': 6}
        >>> merge_dictionaries_advanced(dict1, dict2, dict3)
        {'a': 1, 'b': 3, 'c': 5, 'd': 6}
    """
    if not dicts:
        return {}

    # 验证所有输入都是字典
    for i, d in enumerate(dicts):
        if not isinstance(d, dict):
            raise TypeError(f"第 {i + 1} 个参数不是字典类型")

    conflict_handler = kwargs.get('conflict_handler', 'last')

    if conflict_handler == 'first':
        # 保留第一个出现的值
        merged_dict = {}
        for d in reversed(dicts):  # 反向遍历，先处理后面的
            merged_dict.update(d)
        # 再次反向更新以保持第一个值的优先级
        for d in dicts:
            merged_dict.update(d)

    elif conflict_handler == 'last':
        # 保留最后一个出现的值（默认行为）
        merged_dict = {}
        for d in dicts:
            merged_dict.update(d)

    elif conflict_handler == 'error':
        # 遇到冲突时抛出异常
        merged_dict = {}
        for d in dicts:
            # 检查冲突
            common_keys = set(merged_dict.keys()) & set(d.keys())
            if common_keys:
                raise ValueError(f"键冲突: {common_keys}")
            merged_dict.update(d)
    else:
        raise ValueError("conflict_handler 必须是 'first', 'last' 或 'error'")

    return merged_dict


def merge_with_custom_resolver(dict1, dict2, resolver=None):
    """
    使用自定义解析器合并字典

    Args:
        dict1 (dict): 第一个字典
        dict2 (dict): 第二个字典
        resolver (callable): 冲突解析函数，接受 (key, value1, value2) 返回解析后的值

    Returns:
        dict: 合并后的字典

    Example:
        >>> def sum_resolver(key, v1, v2):
        ...     return v1 + v2
        >>> dict1 = {'a': 1, 'b': 2}
        >>> dict2 = {'b': 3, 'c': 4}
        >>> merge_with_custom_resolver(dict1, dict2, sum_resolver)
        {'a': 1, 'b': 5, 'c': 4}
    """
    if not isinstance(dict1, dict) or not isinstance(dict2, dict):
        raise TypeError("两个参数都必须是字典类型")

    merged_dict = dict1.copy()

    for key, value2 in dict2.items():
        if key in merged_dict:
            if resolver:
                # 使用自定义解析器处理冲突
                value1 = merged_dict[key]
                merged_dict[key] = resolver(key, value1, value2)
            else:
                # 默认行为：后者覆盖前者
                merged_dict[key] = value2
        else:
            merged_dict[key] = value2

    return merged_dict


# 测试函数和示例
def test_merge_dictionaries():
    """测试合并字典函数"""
    print("测试 merge_dictionaries 函数")
    print("=" * 50)

    # 测试用例
    test_cases = [
        # (dict1, dict2, expected_result, description)
        (
            {'a': 1, 'b': 2},
            {'b': 3, 'c': 4},
            {'a': 1, 'b': 3, 'c': 4},
            "基本测试 - 重复键被覆盖"
        ),
        (
            {'x': 10, 'y': 20},
            {'z': 30},
            {'x': 10, 'y': 20, 'z': 30},
            "无重复键测试"
        ),
        (
            {},
            {'a': 1, 'b': 2},
            {'a': 1, 'b': 2},
            "空字典测试1"
        ),
        (
            {'a': 1, 'b': 2},
            {},
            {'a': 1, 'b': 2},
            "空字典测试2"
        ),
        (
            {},
            {},
            {},
            "两个空字典"
        ),
        (
            {'name': 'Alice', 'age': 25},
            {'age': 26, 'city': 'Beijing'},
            {'name': 'Alice', 'age': 26, 'city': 'Beijing'},
            "实际用例测试"
        )
    ]

    all_passed = True

    for i, (dict1, dict2, expected, description) in enumerate(test_cases, 1):
        try:
            result = merge_dictionaries(dict1, dict2)
            passed = result == expected
            status = "通过" if passed else "失败"

            print(f"测试 {i}: {description}")
            print(f"  字典1: {dict1}")
            print(f"  字典2: {dict2}")
            print(f"  期望: {expected}")
            print(f"  实际: {result}")
            print(f"  状态: {status}")
            print()

            if not passed:
                all_passed = False

        except Exception as e:
            print(f"测试 {i}: {description}")
            print(f"  错误: {e}")
            print(f"  状态: 异常")
            print()
            all_passed = False

    # 测试错误处理
    print("测试错误处理:")
    try:
        merge_dictionaries("not_a_dict", {'a': 1})
        print("类型错误测试失败")
        all_passed = False
    except TypeError:
        print("类型错误测试通过")

    return all_passed


def demonstrate_advanced_features():
    """演示高级功能"""
    print("\n🎯 高级功能演示")
    print("=" * 50)

    dict1 = {'a': 1, 'b': 2, 'c': 3}
    dict2 = {'b': 20, 'c': 30, 'd': 40}
    dict3 = {'c': 300, 'e': 50}

    print("原始字典:")
    print(f"  dict1: {dict1}")
    print(f"  dict2: {dict2}")
    print(f"  dict3: {dict3}")
    print()

    # 基本合并
    basic_result = merge_dictionaries(dict1, dict2)
    print(f"基本合并 (dict1 + dict2): {basic_result}")

    # 多字典合并
    multi_result = merge_dictionaries_advanced(dict1, dict2, dict3)
    print(f"多字典合并: {multi_result}")

    # 保留第一个值
    first_result = merge_dictionaries_advanced(dict1, dict2, dict3, conflict_handler='first')
    print(f"保留第一个值: {first_result}")

    # 自定义解析器
    def concatenate_resolver(key, v1, v2):
        return f"{v1}_{v2}"

    custom_result = merge_with_custom_resolver(dict1, dict2, concatenate_resolver)
    print(f"自定义解析器 (连接): {custom_result}")

    # 求和解析器
    def sum_resolver(key, v1, v2):
        return v1 + v2

    sum_result = merge_with_custom_resolver(dict1, dict2, sum_resolver)
    print(f"自定义解析器 (求和): {sum_result}")


def performance_comparison():
    """性能比较不同的合并方法"""
    print("\n⚡ 性能比较")
    print("=" * 50)

    import time

    # 创建测试数据
    dict1 = {f'key_{i}': i for i in range(1000)}
    dict2 = {f'key_{i}': i * 2 for i in range(500, 1500)}

    # 方法1: 使用copy和update
    start = time.time()
    result1 = dict1.copy()
    result1.update(dict2)
    time1 = time.time() - start

    # 方法2: 使用字典推导式
    start = time.time()
    result2 = {k: v for d in [dict1, dict2] for k, v in d.items()}
    time2 = time.time() - start

    # 方法3: 使用 ** 操作符 (Python 3.5+)
    start = time.time()
    result3 = {**dict1, **dict2}
    time3 = time.time() - start

    print(f"copy() + update(): {time1:.6f} 秒")
    print(f"字典推导式: {time2:.6f} 秒")
    print(f"** 操作符: {time3:.6f} 秒")
    print(f"结果相等: {result1 == result2 == result3}")


def main():
    """主函数"""
    print("字典合并工具")
    print("=" * 50)

    # 运行测试
    if test_merge_dictionaries():
        print("所有测试通过！")
    else:
        print("部分测试失败！")

    # 演示高级功能
    demonstrate_advanced_features()

    # 性能比较
    performance_comparison()

    # 交互式示例
    print("\n交互式示例")
    print("=" * 50)

    # 用户输入示例
    try:
        # 示例1
        user_dict1 = {'name': '张三', 'age': 25, 'city': '北京'}
        user_dict2 = {'age': 26, 'job': '工程师', 'city': '上海'}

        print("示例:")
        print(f"字典1: {user_dict1}")
        print(f"字典2: {user_dict2}")

        merged = merge_dictionaries(user_dict1, user_dict2)
        print(f"合并结果: {merged}")

        # 使用自定义解析器
        def keep_both_resolver(key, v1, v2):
            return f"{v1} 或 {v2}"

        custom_merged = merge_with_custom_resolver(user_dict1, user_dict2, keep_both_resolver)
        print(f"自定义合并 (保留两者): {custom_merged}")

    except Exception as e:
        print(f"错误: {e}")


# 简洁的单行版本
def merge_dicts_simple(dict1, dict2):
    """简洁版本的字典合并"""
    return {**dict1, **dict2}


if __name__ == "__main__":
    main()

    # 快速使用示例
    print("\n快速使用:")
    dict_a = {'apple': 1, 'banana': 2}
    dict_b = {'banana': 3, 'cherry': 4}

    result = merge_dictionaries(dict_a, dict_b)
    print(f"合并 {dict_a} 和 {dict_b} = {result}")